package com.feityz.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feityz.system.dao.RoleDeptMapper;
import com.feityz.system.entity.*;
import com.feityz.system.input.RoleDeptInput;
import com.feityz.system.input.RoleDeptQueryInput;
import com.feityz.system.service.*;
import com.feityz.system.vo.RoleDeptUserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleDeptServiceImpl extends ServiceImpl<RoleDeptMapper, RoleDept> implements IRoleDeptService {
    @Autowired
    private IRoleDeptUserService roleDeptUserService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeptService deptService;

    @Override
    @Transactional
    public void saveRelation(RoleDeptInput input){
        Assert.isTrue(input.getDept()!=null,"请传入部门字段");
        Assert.isTrue(input.getRoleId()!=null,"请传入角色字段");
        Assert.isTrue(CollectionUtil.isNotEmpty(input.getUserId()),"请传入人员");

        RoleDept roleDept = new RoleDept();
        roleDept.setDeptNum(input.getDept());
        roleDept.setRoleId(input.getRoleId());
        if(input.getId()==null) {
            //查找重复的
            //新增
            List<RoleDept> list = lambdaQuery().eq(RoleDept::getDeptNum, input.getDept())
                    .eq(RoleDept::getRoleId, input.getRoleId())
                    .list();
            Assert.isTrue(CollectionUtil.isEmpty(list),"重复数据");
            this.save(roleDept);
        }else{
            roleDept.setId(input.getId());
            //修改
            List<RoleDept> list = lambdaQuery().eq(RoleDept::getDeptNum, input.getDept())
                    .ne(RoleDept::getId,input.getId())
                    .eq(RoleDept::getRoleId, input.getRoleId())
                    .list();
            Assert.isTrue(CollectionUtil.isEmpty(list),"重复数据");

            List<RoleDeptUser> roleAreaUsers = roleDeptUserService.lambdaQuery().eq(RoleDeptUser::getRoleDeptId, roleDept.getId()).list();

            roleDeptUserService.removeByIds(roleAreaUsers.stream().map(e->e.getId()).collect(Collectors.toList()));

        }


        if(CollectionUtil.isNotEmpty(input.getUserId())){
            for (Long userId : input.getUserId()) {
                RoleDeptUser roleDeptUser = new RoleDeptUser();
                roleDeptUser.setRoleDeptId(roleDept.getId());
                roleDeptUser.setUserId(userId);
                roleDeptUserService.save(roleDeptUser);
            }
        }
    }

    @Override
    public List<RoleDeptUserVo> listAll(RoleDeptQueryInput input){

        List<RoleDeptUserVo> result = new ArrayList<>();

        List<RoleDept> roleDepts = lambdaQuery()
                .eq(StringUtils.isNotEmpty(input.getDept()),RoleDept::getDeptNum,input.getDept())
                .inSql(StringUtils.isNotEmpty(input.getRoleName()),RoleDept::getRoleId,"select id from sys_role where role_name like '%"+input.getRoleName()+"%'")
                .orderByAsc(RoleDept::getRoleId).list();

        for (RoleDept roleDept : roleDepts) {

            RoleDeptUserVo vo = new RoleDeptUserVo();

            vo.setId(roleDept.getId());

            vo.setDept(roleDept.getDeptNum());

            Dept dept = deptService.lambdaQuery().eq(Dept::getDeptNum,vo.getDept()).one();

            if(dept!=null){
                vo.setDeptName(dept.getDeptName());
            }

            Role role = roleService.lambdaQuery().eq(Role::getId,roleDept.getRoleId()).one();

            if(role !=null) {
                vo.setRoleName(role.getRoleName());
                vo.setRoleId(role.getId());
            }

            List<Long> userIds = roleDeptUserService.lambdaQuery().eq(RoleDeptUser::getRoleDeptId,roleDept.getId())
                    .list().stream().map(e->e.getUserId()).collect(Collectors.toList());

            if(CollectionUtil.isNotEmpty(userIds)) {
                List<User> users = userService.lambdaQuery().in(User::getId, userIds).list();

                String userName = StringUtils.join(users.stream().map(e -> e.getUserName()).collect(Collectors.toList()), ",");

                vo.setUserId(userIds);

                vo.setUserNames(userName);
            }

            result.add(vo);
        }

        return result;
    }

    @Transactional
    @Override
    public void delete(Long id){
        List<RoleDeptUser> roleAreaUsers = roleDeptUserService.lambdaQuery().eq(RoleDeptUser::getRoleDeptId, id).list();
        if(CollectionUtil.isNotEmpty(roleAreaUsers)){
            roleDeptUserService.removeByIds(roleAreaUsers.stream().map(e->e.getId()).collect(Collectors.toList()));
        }
        //删除主表
        removeById(id);
    }

}
